<template>
  <t-dialog
    v-model:visible="dialogVisible"
    :header="dialogTitle"
    width="800px"
    :footer="false"
  >
    <div class="caption-preview">
      <div class="caption-toolbar">
        <t-space>
          <t-tag theme="primary">{{ captionFormat.toUpperCase() }}</t-tag>
          <t-button size="small" @click="copyToClipboard">
            <template #icon><CopyIcon /></template>
            复制
          </t-button>
          <t-button size="small" theme="primary" @click="downloadCaption">
            <template #icon><DownloadIcon /></template>
            下载
          </t-button>
        </t-space>
      </div>

      <div class="caption-content" v-loading="loading">
        <t-textarea
          v-if="!loading"
          v-model="captionContent"
          :autosize="{ minRows: 10 }"
          placeholder="请输入字幕内容..."
        />
        <div v-else class="loading-text">加载字幕内容中...</div>
      </div>

      <t-button size="small" theme="success" @click="saveCaption">
        <template #icon><SaveIcon /></template>
        保存
      </t-button>

    </div>
  </t-dialog>
</template>

<script setup>
import { ref, watch, computed } from 'vue'
import { MessagePlugin, NotifyPlugin } from 'tdesign-vue-next'
import { CopyIcon, DownloadIcon, SaveIcon } from 'tdesign-icons-vue-next'
import { getCaptionContent, downloadCaptionFile, getCaptionContentWithPath } from '@renderer/api/ttsHistory'
import { Client } from '@renderer/client'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  historyId: {
    type: Number,
    default: null
  },
  title: {
    type: String,
    default: ''
  },
  captionPath: {
    type: String,
    default: ''
  }
})

const emit = defineEmits(['update:visible'])

// 使用内部状态管理对话框显示
const dialogVisible = ref(false)
const loading = ref(false)
const captionContent = ref('')
const captionPath = ref('')
const captionFormat = ref('srt')

const dialogTitle = computed(() => {
  return props.title ? `字幕编辑 - ${props.title}` : '字幕编辑'
})

// 监听 props.visible 的变化
watch(() => props.visible, (newVal) => {
  dialogVisible.value = newVal
  if (newVal && props.historyId) {
    loadCaptionContent(true)
  }

  if (newVal && props.captionPath) {
    loadCaptionContent(false)
  }
})

// 监听内部 dialogVisible 的变化，同步到父组件
watch(dialogVisible, (newVal) => {
  if (!newVal) {
    captionContent.value = ''
    emit('update:visible', false)
  }
})

// 加载字幕内容
const loadCaptionContent = async (flag) => {
  try {
    loading.value = true
    let result;
    if (flag){
      result = await getCaptionContent(props.historyId)
    }else {
      result = await getCaptionContentWithPath(props.captionPath)
    }
    captionContent.value = result.content
    captionFormat.value = result.format || 'srt'
    captionPath.value = result.caption_path
  } catch (error) {
    console.error('加载字幕内容失败:', error)
    MessagePlugin.error('加载字幕内容失败: ' + (error.message || '未知错误'))
    // 加载失败时关闭对话框
    dialogVisible.value = false
  } finally {
    loading.value = false
  }
}

// 复制到剪贴板
const copyToClipboard = async () => {
  try {
    await navigator.clipboard.writeText(captionContent.value)
    MessagePlugin.success('已复制到剪贴板')
  } catch (error) {
    // 如果 navigator.clipboard 不可用，使用备用方法
    try {
      const textarea = document.createElement('textarea')
      textarea.value = captionContent.value
      textarea.style.position = 'fixed'
      textarea.style.opacity = '0'
      document.body.appendChild(textarea)
      textarea.select()
      document.execCommand('copy')
      document.body.removeChild(textarea)
      await MessagePlugin.success('已复制到剪贴板')
    } catch (err) {
      await MessagePlugin.error('复制失败: ' + (err.message || '未知错误'))
    }
  }
}

// 下载字幕
const downloadCaption = async () => {
  try {
    const result = await downloadCaptionFile(props.historyId)
    if (result.success) {
      await NotifyPlugin.success({
        title: '下载成功',
        content: '字幕文件已保存'
      })
    }
  } catch (error) {
    await MessagePlugin.error('下载失败: ' + (error.message || '未知错误'))
  }
}

const saveCaption = async () => {
  if (!captionPath.value) {
    await MessagePlugin.error('字幕路径无效，无法保存')
    return
  }

  const result = await Client.file.saveCaption(captionPath.value, captionContent.value);

  if (result.success){
    await MessagePlugin.success(result.message);
    await loadCaptionContent()
  }else {
    await MessagePlugin.error(result.message)
  }
}
</script>

<style lang="less" scoped>
.caption-preview {
  display: flex;
  flex-direction: column;
  height: 500px;

  .caption-toolbar {
    margin-bottom: 16px;
    padding-bottom: 12px;
    border-bottom: 1px solid var(--td-border-level-1-color);
  }

  .caption-content {
    flex: 1;
    overflow: auto;
    background-color: var(--td-bg-color-container);
    border: 1px solid var(--td-border-level-2-color);
    border-radius: var(--td-radius-default);
    padding: 16px;

    pre {
      margin: 0;
      white-space: pre-wrap;
      word-wrap: break-word;
      font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
      font-size: 14px;
      line-height: 1.6;
      color: var(--td-text-color-primary);
    }

    .loading-text {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 100%;
      color: var(--td-text-color-placeholder);
    }

    &::-webkit-scrollbar {
      width: 8px;
      height: 8px;
    }

    &::-webkit-scrollbar-track {
      background: transparent;
    }

    &::-webkit-scrollbar-thumb {
      background-color: var(--td-scrollbar-color);
      border-radius: 4px;

      &:hover {
        background-color: var(--td-scrollbar-hover-color);
      }
    }
  }
}

// 确保对话框的关闭按钮可点击
:deep(.t-dialog__close) {
  cursor: pointer;
  z-index: 1;

  &:hover {
    color: var(--td-text-color-primary);
  }
}
</style>
